<?php
declare(strict_types=1);

namespace Modules\WeChat\Service;

use DB;
use HiCommon\Repository\ShopRepository;
use HiCommon\Repository\ShopCompanyRepository;

use HiCommon\Repository\AdminsRepository;
use HiCommon\Repository\OrderRepairstoreRepository;
use HiCommon\Repository\OrderMallRepository;
use HiCommon\Repository\OrderCheckpointRepository;
use HiCommon\Repository\OrderCheckpointVehicleRepository;

class ShopService extends BaseService
{
    /**
     * 入驻提交数据验证（暂时废弃）
     */
    /*public function checkData($postData)
    {
        $shop = $postData['shop'];
        $company = $postData['company'];
        if (empty($shop['name'])) {
            return ['code' => 1, 'smg' => '门店名称不能为空'];
        }
        if (empty($shop['cate'])) {
            return ['code' => 1, 'smg' => '门店类型不能为空'];
        }
        if (empty($shop['logo'])) {
            return ['code' => 1, 'smg' => '门店logo不能为空'];
        }
        if (empty($shop['phone'])) {
            return ['code' => 1, 'smg' => '门店电话不能为空'];
        }
        if (empty($shop['address'])) {
            return ['code' => 1, 'smg' => '门店详细地址不能为s空'];
        }
        if (empty($shop['province'])) {
            return ['code' => 1, 'smg' => '门店所在的省份id不能为空'];
        }
        if (empty($shop['city'])) {
            return ['code' => 1, 'smg' => '门店所在的城市id不能为空'];
        }
        if (empty($shop['area'])) {
            return ['code' => 1, 'smg' => '门店所在的区域id不能为空'];
        }
        if (empty($shop['longitude'])) {
            return ['code' => 1, 'smg' => '门店经度不能为空'];
        }
        if (empty($shop['latitude'])) {
            return ['code' => 1, 'smg' => '门店纬度不能为空'];
        }

        if (empty($company['company'])) {
            return ['code' => 1, 'smg' => '公司名称不能为空'];
        }
        if (empty($company['person'])) {
            return ['code' => 1, 'smg' => '公司法人不能为空'];
        }
        if (empty($company['phone'])) {
            return ['code' => 1, 'smg' => '法人电话不能为空'];
        }
        if (empty($company['license'])) {
            return ['code' => 1, 'smg' => '三证合一照不能为空'];
        }

        return ['code' => 0, 'smg' => 'ok', 'shop' => $shop, 'company' => $company];
    }*/

    /**
     * 公证号入驻申请（加入我们）（暂时废弃）
     */
    /*public function create($postData)
    {
        try {
            DB::beginTransaction();
            $thisData = self::checkData($postData);
            if ($thisData['code'] == 1) {
                return hello_error($thisData['smg']);
            }

            $shop = ShopRepository::add_one($thisData['shop']);
            if ($shop){
                $thisData['company']['shop_id'] = $shop->id;
                $company = ShopCompanyRepository::add_one($thisData['company']);

                if($company){

                    DB::commit();
                    return hello_success('申请成功等待审核', $shop);
                }
            }

        } catch (\Exception $exception) {

            DB::rollBack();
            return hello_error('失败', [], $exception->getMessage());
        }
    }*/


    /**
     * 获取门店详情
     */
    public function getDetail($openid)
    {
        if (empty($openid)) {
            return hello_error('openid不能为空');
        }

        $with = ['shop' => function ($query) {
            $query->with(['province_name', 'city_name', 'area_name']);
        }];
        $detail = AdminsRepository::get_shop_info($with, $openid);
        if ($detail) {
            $shop = $detail->toArray();
            $city = $shop['shop']['province_name']['name'] . $shop['shop']['city_name']['name'] . $shop['shop']['area_name']['name'];

            $res = [
                'id' => $shop['shop']['id'],
                'cate' => $shop['shop']['cate'],
                'name' => $shop['shop']['name'],
                'logo' => $shop['shop']['logo']['full_src'],
                'phone' => $shop['shop']['phone'],
                'address' => $city . ' ' . $shop['shop']['address'],
            ];

            return hello_success('获取成功', $res);
        }

        return hello_error('请登录');
    }

    /**
     * 门店数据统计
     */
    public function statistics($data)
    {
        if (empty($data['cate'])) {
            return hello_error('门店类型不能为空');
        }
        if (empty($data['time_cate'])) {
            return hello_error('日期类型不能为空');
        }

        if ($data['cate'] == 1) {//检测站
            $checkpoint = self::checkpointOrderNum($data);//检测站预约订单

            return hello_success('成功', ['checkpoint' => $checkpoint]);
        } elseif ($data['cate'] == 2) {//维修店

            $goods = self::goodsOrderNum($data);//商品订单统计
            $repair = self::repairOrderNum($data);//服务订单统计

            return hello_success('成功', ['goods' => $goods, 'repair' => $repair]);
        } else {
            return hello_error('门店类型不正确');
        }
    }

    /**
     * 检测站（预约订单统计）
     */
    public function checkpointOrderNum($data)
    {
        $array = self::dateArray($data['time_cate']);
        $order = OrderCheckpointRepository::get_all_by_where(['shop_id' => $data['shop_id']], ['id']);

        $data['order_ids'] = [];
        foreach ($order as $or => $order) {
            $data['order_ids'][] = $order['id'];
        }
        $list = OrderCheckpointVehicleRepository::count_by_where((array)$data, (array)$array);

        $acting = array();
        $price = [];
        foreach ($list[1] as $d => $day) { //代驾
            $acting[$day['date']] = $day['total'];
            $price[$day['date']] = $day['price'];
        }
        $dai = array();
        foreach ($array as $key => $value) {//代驾
            if (array_key_exists($value, $acting)) {
                $dai['num'][$key] = $acting[$value];
                $dai['price'][$key] = $price[$value];
            } else {
                $dai['num'][$key] = 0;
                $dai['price'][$key] = 0;
            }
            $dai['date'][$key] = $value;
        }

        $detail = array();
        $price2 = [];
        foreach ($list[2] as $d => $day) { //自驾
            $detail[$day['date']] = $day['total'];
            $price2[$day['date']] = $day['price'];
        }

        $zi = array();//自驾
        foreach ($array as $key => $value) {
            if (array_key_exists($value, $detail)) {
                $zi['num'][$key] = $detail[$value];
                $zi['price'][$key] = $price2[$value];
            } else {
                $zi['num'][$key] = 0;
                $zi['price'][$key] = 0;
            }
            $zi['date'][$key] = $value;
        }

        return ['zi' => $zi, 'dai' => $dai, 'total' => $list[3]];
    }

    /**
     * 维修店(商品订单)数据统计
     */
    public function goodsOrderNum($data)
    {
        $array = self::dateArray($data['time_cate']);
        //积分订单统计
        $list = OrderMallRepository::count_by_where((int)$data['shop_id'], (int)$data['time_cate'], (array)$array);
        $detail = array();
        foreach ($list[1] as $d => $day) {
            $detail[$day['date']] = $day['total'];
            $integral[$day['date']] = $day['integral'];
        }

        $census = array();
        foreach ($array as $key => $value) {
            if (array_key_exists($value, $detail)) {
                $census['num'][$key] = $detail[$value];
                $census['integral'][$key] = (int)$integral[$value];
            } else {
                $census['num'][$key] = 0;
                $census['integral'][$key] = 0;
            }
            $census['date'][$key] = $value;
        }

        return ['census' => $census, 'total' => $list[3]];
    }

    /**
     * 维修店(服务订单)数据统计
     */
    public function repairOrderNum($data)
    {
        $array = self::dateArray($data['time_cate']);

        if ($data['time_cate'] == 2) {
            $list = OrderRepairstoreRepository::count_by_where_month((int)$data['shop_id'], (array)$array);
        } else {
            $list = OrderRepairstoreRepository::count_by_where_days((int)$data['shop_id'], (array)$array);
        }

        $detail = array();
        $amount = [];
        foreach ($list[1] as $d => $day) { //自驾
            $detail[$day['date']] = $day['total'];
            $amount[$day['date']] = $day['amount'];
        }

        $zi = array();//自驾
        foreach ($array as $key => $value) {
            if (array_key_exists($value, $detail)) {
                $zi['num'][$key] = $detail[$value];
                $zi['amount'][$key] = (float)$amount[$value];
            } else {
                $zi['num'][$key] = 0;
                $zi['amount'][$key] = 0;
            }
            $zi['date'][$key] = $value;
        }

        $acting = array();
        $acamount = [];
        foreach ($list[2] as $d => $day) { //代驾
            $acting[$day['date']] = $day['total'];
            $acamount[$day['date']] = $day['amount'];
        }
        $dai = array();
        foreach ($array as $key => $value) {//代驾
            if (array_key_exists($value, $acting)) {
                $dai['num'][$key] = $acting[$value];
                $dai['amount'][$key] = (float)$acamount[$value];
            } else {
                $dai['num'][$key] = 0;
                $dai['amount'][$key] = 0;
            }
            $dai['date'][$key] = $value;
        }

        return ['zi' => $zi, 'dai' => $dai, 'total' => $list[3]];
    }

    /**
     * 日期计算
     */
    public function dateArray($cate)
    {
        $time = time();
        if ($cate == 1) {
            for ($i = 0; $i <= 6; $i++) {
                $date[$i] = date('Y-m-d', strtotime('+' . $i - 6 . 'days', $time));
            }
        } elseif ($cate == 2) {
            for ($m = 0; $m <= 5; $m++) {
                $date[$m] = date('Y-m', strtotime('+' . $m - 5 . 'month', $time));
            }
        } else {
            $month = date('Y-m', $time);
            $allday = date('d', strtotime("$month +1 month -1 day"));

            for ($d = 1; $d <= $allday; $d++) {
                $day = $d > 9 ? $d : '0' . $d;
                $date[] = $month . '-' . $day;
            }
        }

        return $date ?? [];
    }


    /**
     * 获取维修店的订单记录（积分订单，服务订单，现金订单）
     */
    public function getShopOrder($data)
    {
        dd($data);
    }

}